package jk.zmn.socket.tcp.demo3;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * @author 张梦楠
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @date 2018/5/3119:02
 * @blog www.itzmn.com
 *
 *
 * 线程，发送数据
 */

public class Send implements Runnable {


    private BufferedReader bufferedReader = null;

    private DataOutputStream dataOutputStream = null;

    private boolean isRunning = true;
    private String name; //用户名称

    public Send(Socket socket,String name){
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            dataOutputStream = new DataOutputStream(socket.getOutputStream());
            this.name = name;
            //当建立链接之后，发送姓名给服务端
            send(name);

        } catch (IOException e) {
            //e.printStackTrace();
            isRunning = false;
            CloseUtils.CloseAll(dataOutputStream,bufferedReader);
        }
    }


    public String getConsoleData(){
        try {
            return bufferedReader.readLine();
        } catch (IOException e) {
            isRunning = false;
            CloseUtils.CloseAll(dataOutputStream,bufferedReader);
        }
        return "";
    }

    /**
     * 发送信息的方法
     */
    public void send(String msg){
        try {
            if (msg!=null && !msg.equals("")) {
                dataOutputStream.writeUTF(msg);
                dataOutputStream.flush();
            }

        } catch (IOException e) {
            isRunning = false;
            CloseUtils.CloseAll(dataOutputStream,bufferedReader);
        }
    }


    @Override
    public void run() {

        while (isRunning){
            send(getConsoleData());
        }

    }
}
